<!-- src/components/CartListView.vue -->
<template>
  <scroll-view class="cart-scroll" scroll-y style="max-height: 70vh;">
    <view class="cart_view">
      <!-- 购物车为空 -->
      <view v-if="cartGoods.length === 0" class="empty-cart">
        <wd-icon name="cart" size="60px" color="#ccc" />
        <text class="empty-text">购物车是空的哦~</text>
      </view>

      <!-- 购物车列表 -->
      <view v-else class="cart-list">
        <view v-for="(category, catIndex) in cartCategories" :key="catIndex" class="cart-category">
          <!-- 分类标题 -->
          <view class="category-header">
            <view class="category-selector">
              <wd-checkbox
                v-model="category.checked"
                @change="handleCategoryCheck(catIndex)"
                shape="circle"
                class="checkbox-left"
              />
              <text class="category-name">{{ category.name }}</text>
            </view>
            <wd-button
              type="text"
              text-color="#ff4d4f"
              size="small"
              @click="handleDeleteCategory(catIndex)"
              :disabled="!category.goods.some(item => item.checked)"
            >
              删除分类
            </wd-button>
          </view>

          <!-- 商品列表 -->
          <view class="category-goods">
            <view v-for="(item, itemIndex) in category.goods" :key="item.id" class="cart-item">
              <view class="item-checkbox-col">
                <wd-checkbox
                  v-model="item.checked"
                  @change="handleItemCheck(catIndex, itemIndex)"
                  shape="circle"
                  class="checkbox-left"
                />
              </view>
              <view class="item-content">
                <view class="item-info">
                  <image
                    :src="item.imageUrl || 'https://p0.meituan.net/coverpic/4e9b9e5a742ddfc29f9efb8c7033dbe21323862.jpg'"
                    class="item-img"
                  />
                  <view class="item-details">
                    <text class="item-name">{{ item.name }}</text>
                    <text class="item-price">￥{{ item.price }}</text>
                  </view>
                </view>
                <view class="item-quantity">
                  <view
                    class="count-btn count-btn--minus text11"
                    @click="handleCartCountChange(item, -1)"
                    :class="{ 'count-btn--disabled': item.count <= 1 }"
                  >
                    -
                  </view>
                  <text class="count-btn__num text11">{{ item.count }}</text>
                  <view class="count-btn count-btn--plus text11" @click="handleCartCountChange(item, 1)">
                    +
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 批量操作 -->
        <view class="batch-operation">
          <view class="select-all-wrap">
            <wd-checkbox v-model="selectAll" @change="handleSelectAll" shape="circle" class="checkbox-left" />
            <text class="select-all-text">全选</text>
          </view>
          <wd-button
            type="error"
            size="small"
            @click="handleBatchDelete"
            :disabled="!hasSelectedItems"
            class="batch-delete-btn"
          >
            批量删除
          </wd-button>
        </view>

        <!-- 合计 & 结算 -->
        <view class="cart-summary">
          <view class="summary-info">
            <text class="total-text">合计（仅勾选商品）：</text>
            <text class="total-price">￥{{ cartTotalAmount }}</text>
          </view>
          <wd-button type="primary" class="checkout-btn" :disabled="!hasSelectedItems" @click="handleCheckout">
            结算
          </wd-button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import Decimal from 'decimal.js'

const props = defineProps({
  // 原始分类商品数据（带 count）
  categories: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:categories', 'checkout'])

// 内部状态
const cartCategories = ref([])
const selectAll = ref(false)

// 同步原始数据变更
watch(
  () => props.categories,
  (newVal) => {
    const cartData = []
    newVal.forEach(category => {
      const validGoods = category.foods
        .filter(item => item.count > 0)
        .map(item => {
          const existing = cartCategories.value
            .flatMap(c => c.goods)
            .find(g => g.id === item.id)
          return { ...item, checked: existing?.checked ?? false }
        })

      if (validGoods.length > 0) {
        const existingCat = cartCategories.value.find(c => c.name === category.name)
        cartData.push({
          id: category.id || category.name,
          name: category.name,
          checked: existingCat?.checked ?? false,
          goods: validGoods
        })
      }
    })
    cartCategories.value = cartData
  },
  { deep: true, immediate: true }
)

// 计算属性
const cartGoods = computed(() => cartCategories.value.flatMap(c => c.goods))
const hasSelectedItems = computed(() =>
  cartCategories.value.some(cat => cat.goods.some(item => item.checked))
)
const cartTotalAmount = computed(() => totalAmount.value || '0.00')

// 金额 & 数量
const cartCount = ref(0)
const totalAmount = ref('0.00')

// 更新合计（仅勾选商品）
const updateSelectedTotal = () => {
  let selectedTotal = new Decimal(0)
  let selectedItemCount = 0
  cartCategories.value.forEach(cat => {
    cat.goods.forEach(item => {
      if (item.checked && item.count > 0 && typeof item.price === 'number') {
        selectedTotal = selectedTotal.plus(new Decimal(item.price).times(item.count))
        selectedItemCount += item.count
      }
    })
  })
  cartCount.value = selectedItemCount
  totalAmount.value = selectedTotal.toFixed(2)
}

// 同步回原始数据
const syncToOriginal = () => {
  const originalMap = {}
  props.categories.forEach(cat => {
    cat.foods.forEach(item => {
      originalMap[item.id] = item
    })
  })

  cartCategories.value.forEach(cat => {
    cat.goods.forEach(item => {
      if (originalMap[item.id]) {
        originalMap[item.id].count = item.count
      }
    })
  })
  emit('update:categories', [...props.categories])
}

// 操作方法
const handleCartCountChange = (item, delta) => {
  if (item.count + delta < 1) return
  const checked = item.checked
  item.count += delta
  syncToOriginal()
  item.checked = checked
  if (checked) updateSelectedTotal()
}

const handleCategoryCheck = (idx) => {
  const cat = cartCategories.value[idx]
  cat.goods.forEach(item => (item.checked = cat.checked))
  updateSelectAllStatus()
  updateSelectedTotal()
}

const handleItemCheck = (catIdx, itemIdx) => {
  const cat = cartCategories.value[catIdx]
  cat.checked = cat.goods.every(item => item.checked)
  updateSelectAllStatus()
  updateSelectedTotal()
}

const updateSelectAllStatus = () => {
  selectAll.value = cartCategories.value.length > 0 && cartCategories.value.every(cat => cat.checked)
}

const handleSelectAll = () => {
  cartCategories.value.forEach(cat => {
    cat.checked = selectAll.value
    cat.goods.forEach(item => (item.checked = selectAll.value))
  })
  updateSelectedTotal()
}

const handleDeleteCategory = (catIdx) => {
  const cat = cartCategories.value[catIdx]
  const ids = cat.goods.filter(item => item.checked).map(item => item.id)
  if (ids.length === 0) return

  props.categories.forEach(originCat => {
    if (originCat.name === cat.name) {
      originCat.foods.forEach(item => {
        if (ids.includes(item.id)) item.count = 0
      })
    }
  })
  emit('update:categories', [...props.categories])
  updateSelectedTotal()
  updateSelectAllStatus()
}

const handleBatchDelete = () => {
  cartCategories.value.forEach(cat => {
    const ids = cat.goods.filter(item => item.checked).map(item => item.id)
    props.categories.forEach(originCat => {
      if (originCat.name === cat.name) {
        originCat.foods.forEach(item => {
          if (ids.includes(item.id)) item.count = 0
        })
      }
    })
  })
  emit('update:categories', [...props.categories])
  updateSelectedTotal()
  updateSelectAllStatus()
}

const handleCheckout = () => {
  emit('checkout', cartCategories.value)
}
 

// 弹窗打开时默认全选
defineExpose({ 
       getSelectedData: () => {
    return cartCategories.value
      .map(cat => ({
        ...cat,
        goods: cat.goods.filter(item => item.checked) // 只保留勾选商品
      }))
      .filter(cat => cat.goods.length > 0) // 只保留有勾选商品的分类
  },
  setDefaultSelectAll: () => {
  nextTick(() => {
    selectAll.value = true
    handleSelectAll()
  })
}})
</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/cart-scroll.less");

/* 此处可内联或复用你已有的 cart-scroll.less */
</style>